package com.xzakota.minesweeper;

import com.xzakota.minesweeper.contant.ConstantPool;
import com.xzakota.minesweeper.log.XLogger;
import com.xzakota.minesweeper.ui.dialog.templae.MessageDialog;
import com.xzakota.minesweeper.ui.dialog.templae.OptionDialog;
import com.xzakota.minesweeper.ui.frame.SplashFrame;
import com.xzakota.minesweeper.util.AppUtils;
import com.xzakota.minesweeper.util.JSONFileUtils;

import javax.swing.*;
import java.io.File;

/**
 * 客户端主程序入口类
 *
 * @author Xzakota
 */
public class App {
    public static final String APP_DATA_DIR_PATH = AppUtils.getAppDataDir(ConstantPool.APP_NAME);

    public static void main(String[] args) throws Exception {
        // 捕获全局异常
        Thread.setDefaultUncaughtExceptionHandler((t, e) -> {
            XLogger.error(e.getMessage(), e);
            new MessageDialog(e).showWindow();
        });

        // 设置窗口风格
        for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
            // 风格可选: Metal、Nimbus、CDE/Motif、Windows、Windows Classic
            if ("Windows".equals(info.getName())) {
                UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }

        // 初始化应用设置 JSON
        JSONFileUtils.initJSON(APP_DATA_DIR_PATH + File.separator + "settings.json");

        // 处理异常关闭
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            SingleTaskExecutor.shutdown();
            Client.getClient().close();
            JSONFileUtils.commit();
        }));

        // 创建启动界面并显示
        SwingUtilities.invokeLater(() -> {
            SplashFrame frame = new SplashFrame();
            frame.showWindow();
            XLogger.info("客户端打开启动界面");

            if (JSONFileUtils.has(ConstantPool.SETTINGS_SERVER_IP)) {
                // 连接服务端
                new Thread(() -> {
                    Client.initSocket(JSONFileUtils.getString(ConstantPool.SETTINGS_SERVER_IP));
                    SingleTaskExecutor.submitTask(Client.getClient());
                }).start();
            }
        });
    }

    public static boolean connectServer() {
        if (Client.getClient().socketState != 1) {
            OptionDialog optionDialog = new OptionDialog("当前未与服务器连接，是否重连？");
            optionDialog.setConfirmAction(evt -> {
                optionDialog.setConfirmButtonEnabled(false);
                new Thread(() -> {
                    Client.initSocket(JSONFileUtils.getString(ConstantPool.SETTINGS_SERVER_IP));
                    SingleTaskExecutor.submitTask(Client.getClient());
                    optionDialog.closeWindow();
                    optionDialog.setConfirmButtonEnabled(true);
                }).start();
            });
            optionDialog.showWindow();
            return true;
        }

        return false;
    }
}
